<template>
  <div class="analysis-wrapper">
    <div class="analysis-header">
      <div class="header-title cursor-pointer" @click="goIndex">鹿翎星衡数据分析</div>
      <div class="flex mr-5">
        <n-button
          :bordered="false"
          class="mr-5"
          v-if="currentFileName"
          type="success"
          @click="goIndex"
          >{{ currentFileName }}</n-button
        >
        <n-button class="mr-5" @click="goDataList">我的数据</n-button>
        <n-button type="primary" class="mr-5" @click="uploadData">上传数据</n-button>
        <n-avatar round />
      </div>
    </div>
    <div class="flex" v-if="currentStatus === 1">
      <div class="attribute-wrapper ml-5">
        <div class="p-5 bg-white">
          <div class="flex items-center attribute-header justify-center pb-2">通用方法</div>
          <div class="flex flex-wrap pt-3">
            <n-checkbox
              v-for="cd in commonData"
              :key="cd.name"
              :label="cd.name"
              :disabled="cd.disabled || analysisStatus === 1"
              :checked="cd.is_checked"
              @update:checked="(v) => onConfigChange(cd.name, v)"
              class="w-1/2 mt-5"
            />
          </div>
        </div>
        <div class="p-5 mt-5 bg-white">
          <div class="flex items-center attribute-header justify-center pb-2">问卷研究</div>
          <div class="flex flex-wrap pt-3">
            <n-checkbox
              v-for="ad in analysisData"
              :key="ad.name"
              :label="ad.name"
              :disabled="ad.disabled || analysisStatus === 1"
              :checked="ad.is_checked"
              @update:checked="(v) => onConfigChange(ad.name, v)"
              class="w-1/2 mt-5"
            />
          </div>
        </div>
        <div class="p-5 mt-5 bg-white">
          <div class="flex items-center attribute-header justify-center pb-2">模板选择</div>
          <div class="flex flex-wrap pt-3">
            <n-radio-group v-model:value="tmp" name="radiogroup">
              <n-space>
                <n-radio v-for="t in templateData" :key="t.value" :value="t.value" :disabled="true">
                  {{ t.label }}
                </n-radio>
              </n-space>
            </n-radio-group>
          </div>
        </div>
      </div>
      <div v-if="analysisStatus === 0" class="flex-1 ml-5 bg-white mr-5">
        <n-card title="配置">
          <template #header-extra>
            <n-button type="primary" @click="startAnalysis" :loading="loadingAnalysis"
              >开始分析</n-button
            >
          </template>
          <n-tabs type="line" animated v-model:value="currentTab" ref="tabRef">
            <n-tab-pane
              v-for="algorithm in selectedAlgorithms"
              :key="algorithm.name"
              :name="algorithm.name"
              :tab="algorithm.name"
            >
              <div v-if="currentTab === '全局'">
                <div class="flex mb-5 flex-wrap">
                  <div class="flex items-center mt-5 ml-5">
                    <div style="width: 78px">因变量：</div>
                    <div
                      ><n-select
                        style="width: 200px"
                        :options="canSelectDaGroups"
                        v-model:value="selectedDa"
                        @update:value="updateDa"
                        multiple
                    /></div>
                  </div>
                  <div class="flex items-center ml-5 mt-5">
                    <div style="width: 78px">自变量：</div>
                    <div
                      ><n-select
                        style="width: 200px"
                        :options="canSelectVaGroups"
                        v-model:value="selectedVa"
                        @update:value="updateVa"
                        multiple
                    /></div>
                  </div>
                  <div class="flex items-center ml-5 mt-5">
                    <div style="width: 78px">中介变量：</div>
                    <div
                      ><n-select
                        style="width: 200px"
                        :options="canSelectMaGroups"
                        v-model:value="selectedMa"
                        @update:value="updateMa"
                        multiple
                    /></div>
                  </div>
                  <div class="flex items-center ml-5 mt-5">
                    <div style="width: 78px">调节变量：</div>
                    <div
                      ><n-select
                        style="width: 200px"
                        :options="canSelectWaGroups"
                        v-model:value="selectedWa"
                        @update:value="updateWa"
                        multiple
                    /></div>
                  </div>
                  <div class="flex items-center ml-5 mt-5">
                    <div style="width: 78px">控制变量：</div>
                    <div
                      ><n-select
                        style="width: 200px"
                        :options="canSelectCa"
                        v-model:value="selectedCa"
                        multiple
                    /></div>
                  </div>
                </div>
                <div>
                  <div>
                    <n-button type="primary" class="mb-5" @click="addGroup">添加分组</n-button>
                    <n-data-table :data="groupData" :columns="groupColumns" />
                    <n-modal :show="showAddModal" style="width: 50%">
                      <n-card title="新增分组">
                        <template #header-extra>
                          <n-button :bordered="false" @click="() => (showAddModal = false)"
                            >x</n-button
                          >
                        </template>
                        <n-transfer
                          :options="canSelectGroupTopics"
                          v-model:value="groupValue"
                          source-filterable
                          target-filterable
                          :render-source-label="renderSourceLabel"
                          :render-target-label="renderSourceLabel"
                        />
                        <template #action>
                          <div class="flex justify-end">
                            <n-space>
                              <n-button @click="() => (showAddModal = false)">取消</n-button>
                              <n-button type="primary" @click="confirmAddGroup">确定</n-button>
                            </n-space>
                          </div>
                        </template>
                      </n-card>
                    </n-modal>
                  </div>
                </div>
              </div>
              <div
                v-if="currentTab === '效度'"
                class="flex items-center w-full justify-center text-slate-500"
                >复用全局的配置</div
              >
              <div
                v-if="currentTab === '信度'"
                class="flex items-center w-full justify-center text-slate-500"
                >复用全局的配置</div
              >
              <div v-if="currentTab === '频数'">
                <n-transfer
                  :options="commonTopics"
                  v-model:value="selectedPinshuTopics"
                  source-filterable
                  target-filterable
                  virtual-scroll
                  :render-source-label="renderSourceLabel"
                  :render-target-label="renderSourceLabel"
                />
              </div>
              <div v-if="currentTab === '描述'">
                <n-transfer
                  :options="commonTopics"
                  v-model:value="selectedDesTopics"
                  source-filterable
                  target-filterable
                  virtual-scroll
                  :render-source-label="renderSourceLabel"
                  :render-target-label="renderSourceLabel"
                />
              </div>
              <div v-if="currentTab === '多重响应'">
                <!-- <n-transfer
                  :options="commonTopics"
                  v-model:value="selectedResponseTopics"
                  source-filterable
                  target-filterable
                  :render-source-label="renderSourceLabel"
                  :render-target-label="renderSourceLabel"
                /> -->
                <div>
                  <div>
                    <n-button type="primary" class="mb-5" @click="addReponseGroup"
                      >添加分组</n-button
                    >
                    <n-data-table :data="responseGroupData" :columns="groupColumns1" />
                    <n-modal :show="showResponseModal" style="width: 50%">
                      <n-card title="新增分组">
                        <template #header-extra>
                          <n-button :bordered="false" @click="() => (showResponseModal = false)"
                            >x</n-button
                          >
                        </template>
                        <n-transfer
                          :options="canSelectResponseGroupTopics"
                          v-model:value="groupResponseValue"
                          source-filterable
                          target-filterable
                          virtual-scroll
                          :render-source-label="renderSourceLabel"
                          :render-target-label="renderSourceLabel"
                        />
                        <template #action>
                          <div class="flex justify-end">
                            <n-space>
                              <n-button @click="() => (showResponseModal = false)">取消</n-button>
                              <n-button type="primary" @click="confirmAddResponseGroup"
                                >确定</n-button
                              >
                            </n-space>
                          </div>
                        </template>
                      </n-card>
                    </n-modal>
                  </div>
                </div>
              </div>
              <div v-if="currentTab === '中介'">
                <div class="flex items-center mt-10 justify-center">
                  <div class="flex-1 text-right mr-5">bootstrap抽样次数：</div>
                  <div class="flex-1"
                    ><n-select
                      :options="intermediaryCountOptions"
                      v-model:value="selectedintermediaryCount"
                      style="width: 300px"
                  /></div>
                </div>
                <div class="flex items-center mt-8 justify-center">
                  <div class="flex-1 text-right mr-5">中介类型：</div>
                  <div class="flex-1"
                    ><n-select
                      :options="intermediaryTypeOptions"
                      v-model:value="selectedintermediaryType"
                      style="width: 300px"
                  /></div>
                </div>
              </div>
              <div v-if="currentTab === '调节'">
                <div class="flex items-center mt-10 justify-center">
                  <div class="flex-1 text-right mr-5">数据处理：</div>
                  <div class="flex-1"
                    ><n-select
                      :options="adjustDataOptions"
                      v-model:value="adjustDataValue"
                      style="width: 300px"
                  /></div>
                </div>
                <div class="flex items-center mt-8 justify-center">
                  <div class="flex-1 text-right mr-5">模型选择：</div>
                  <div class="flex-1"
                    ><n-select
                      :options="modernOptions"
                      v-model:value="modernValue"
                      style="width: 300px"
                  /></div>
                </div>
              </div>
              <div v-if="currentTab === 'T检验'">
                <div class="flex items-center mt-10 justify-center">
                  <div class="flex-1 text-right mr-5">X变量：</div>
                  <div class="flex-1"
                    ><n-select
                      :options="commonTopics"
                      v-model:value="txValue"
                      multiple
                      style="width: 300px"
                  /></div>
                </div>
                <div class="flex items-center mt-8 justify-center">
                  <div class="flex-1 text-right mr-5">Y变量：</div>
                  <div class="flex-1"
                    ><n-select
                      :options="commonGroupData"
                      v-model:value="tyValue"
                      multiple
                      style="width: 300px"
                  /></div>
                </div>
              </div>
              <div v-if="currentTab === '方差'">
                <div class="flex items-center mt-10 justify-center">
                  <div class="flex-1 text-right mr-5">X变量：</div>
                  <div class="flex-1"
                    ><n-select
                      :options="commonTopics"
                      v-model:value="varianceXValue"
                      multiple
                      style="width: 300px"
                  /></div>
                </div>
                <div class="flex items-center mt-8 justify-center">
                  <div class="flex-1 text-right mr-5">Y变量：</div>
                  <div class="flex-1"
                    ><n-select
                      :options="commonGroupData"
                      v-model:value="varianceYValue"
                      multiple
                      style="width: 300px"
                  /></div>
                </div>
              </div>
              <div
                v-if="currentTab === '结构模型'"
                class="flex flex-col items-center mt-10 justify-center"
              >
                <div
                  class="flex items-center mb-5"
                  v-for="verifyEquation in verifyEquationGroups"
                  :key="verifyEquation.sort"
                >
                  <div
                    ><n-input disabled :default-value="verifyEquation.fromName.toString()"
                  /></div>
                  <div class="ml-2" style="color: rgb(103, 102, 103); font-size: 12px">影响→</div>
                  <div class="ml-2"
                    ><n-input disabled :default-value="verifyEquation.toName.toString()"
                  /></div>
                  <div class="flex items-center">
                    <n-button
                      class="ml-2"
                      type="error"
                      v-if="verifyEquation.is_selected"
                      @click="delVerifyGroup(verifyEquation)"
                      >移除</n-button
                    >
                    <n-button
                      class="ml-2"
                      type="primary"
                      v-else
                      @click="addVerifyGroup(verifyEquation)"
                      >添加</n-button
                    >
                  </div>
                </div>
              </div>
              <div
                v-if="currentTab === '验证性分析'"
                class="flex flex-col items-center mt-10 justify-center"
              >
                <div
                  class="flex items-center mb-5"
                  v-for="structure in structureModelGroups"
                  :key="structure.sort"
                >
                  <div><n-input disabled :default-value="structure.fromName.toString()" /></div>
                  <div class="ml-2" style="color: rgb(103, 102, 103); font-size: 12px">←影响→</div>
                  <div class="ml-2"
                    ><n-input disabled :default-value="structure.toName.toString()"
                  /></div>
                  <div class="flex items-center">
                    <n-button
                      class="ml-2"
                      type="error"
                      v-if="structure.is_selected"
                      @click="delStructure(structure)"
                      >移除</n-button
                    >
                    <n-button class="ml-2" type="primary" v-else @click="addStructure(structure)"
                      >添加</n-button
                    >
                  </div>
                </div>
              </div>
              <div
                v-if="currentTab === '相关'"
                class="flex items-center w-full justify-center text-slate-500"
                >复用全局的配置</div
              >
              <div
                v-if="currentTab === '回归'"
                class="flex items-center w-full justify-center text-slate-500"
                >复用全局的配置</div
              >
            </n-tab-pane>
          </n-tabs>
        </n-card>
      </div>
      <div v-if="analysisStatus === 1" class="flex-1 ml-5 mr-5">
        <div class="w-full bg-white flex items-center mb-5" style="height: 60px">
          <n-space>
            <n-button @click="downloadPdf" type="success" class="ml-5">导出PDF</n-button>
            <n-button @click="downloadWord" type="success">导出Word</n-button>
          </n-space>
        </div>
        <div ref="docWrapper"></div>
      </div>
    </div>
    <div
      v-if="currentStatus === 2"
      style="color: #555"
      class="flex justify-center flex-col items-center"
    >
      <div>
        <img :src="uploadImg" />
      </div>
      <div v-if="uploadStatus === 1" class="flex justify-center flex-col items-center w-1/2">
        <div class="mt-8 bg-white p-5">
          <div class="flex">
            <n-upload :max="1" :action="uploadDataUrl" :custom-request="customRequest">
              <n-upload-dragger>
                <div style="margin-bottom: 12px">
                  <n-icon size="48" :depth="3">
                    <archive-icon />
                  </n-icon>
                </div>
                <n-text style="font-size: 14px"> 点击或者拖动文件到该区域来上传 </n-text>
                <n-p depth="3" style="margin: 8px 0 0 0"> 支持EXCEL/SPSS/Stata/SAS文件 </n-p>
              </n-upload-dragger>
            </n-upload>
            <div class="ml-5">
              <li>导入说明： </li>
              <li>1、支持xls、xlsx、csv、sav、dta、sas7bdat等格式 </li>
              <li>2、不能合并单元格</li>
              <li>3、第1行是标题不能缺失 </li>
              <li>4、文件在10M内，最高5万行，1024列</li>
              <li>5、日期字段需包含年月日（如2021/1/1），或 年月日时分秒（如2021/1/1 00:00:00）</li>
              <li>6、若有问题可查看上传详细说明</li>
            </div>
          </div>
          <div style="font-size: 16px" class="mt-5 mb-5">表格示例</div>
          <n-data-table :data="uploadExampleData" :columns="uploadExampleColumns" />
        </div>
      </div>
      <div v-else class="flex justify-center flex-col items-left w-1/2 bg-white p-8 mt-8">
        <div class="flex items-center mb-2">
          <div>数据文档名称：</div>
          <div style="width: 300px"><n-input v-model:value="uploadFileName" disabled /></div>
        </div>
        <div class="flex items-center mb-2">
          <div>当前样本量：</div>
          <div>{{ uploadDataLength }}</div>
        </div>
        <div class="mb-5">数据预览（前20条）如下</div>
        <n-data-table :data="previewUploadData" :columns="previewUploadColumns" :max-height="200" />
        <div class="mt-8 flex justify-center">
          <n-button class="mr-10" @click="preStep">上一步</n-button>
          <n-button type="primary" @click="goAnalysis">进入分析</n-button>
        </div>
      </div>
    </div>
    <div v-if="currentStatus === 3" class="flex justify-center items-center">
      <div class="bg-white p-8 w-1/2">
        <div class="flex items-center justify-between mb-10">
          <div style="color: #178aec; font-weight: bold">SPSS案例数据集</div>
          <div><n-button type="primary" @click="uploadData">上传数据</n-button></div>
        </div>
        <div class="mb-5" v-if="currentAnalysis && currentAnalysis.length">
          <div style="color: #178aec; font-size: 12px" class="mb-5">正在分析</div>
          <n-data-table :data="currentAnalysis" :columns="createAnalysisColumns('current')" />
        </div>
        <div class="mb-5">
          <div style="color: #178aec; font-size: 12px" class="mb-5">全部文档</div>
          <n-spin :show="showFiles">
            <n-data-table
              :data="allAnalysis"
              :columns="createAnalysisColumns('all')"
              :row-key="(record) => record.record_id"
              striped
            />
          </n-spin>
        </div>
        <div class="flex justify-end mt-5">
          <n-pagination
            v-model:page="page"
            v-model:page-size="pageSize"
            :page-count="pageCount"
            show-size-picker
            :page-sizes="[10, 20, 30, 40]"
            @update:page="pullList"
            @update:page-size="pullList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref, h, unref, toRaw } from 'vue';
  import { NTooltip, NInput, NCheckbox, NButton, NSpace } from 'naive-ui';
  import UploadDataImg1 from '@/assets/images/upload_data_1.png';
  import UploadDataImg2 from '@/assets/images/upload_data_2.png';
  import { ArchiveOutline as ArchiveIcon } from '@vicons/ionicons5';
  import { useGlobSetting } from '@/hooks/setting';
  import { nextTick } from 'vue';
  import { onMounted } from 'vue';
  import { useMessage, UploadCustomRequestOptions } from 'naive-ui';
  import {
    algorithmAnalysis,
    serachData,
    listFile,
    deleteFile,
    modifyFileName,
    queryConfig,
  } from '@/api/analysis';
  import { useRouter, useRoute } from 'vue-router';
  import dayjs from 'dayjs';
  import * as docx from 'docx-preview';
  import { lyla } from '@lylajs/web';
  const message = useMessage();
  const globSetting = useGlobSetting();
  const router = useRouter();
  const route = useRoute();
  const docWrapper: any = ref(null);
  // 正在分析文档名称
  const currentFileName: any = ref(null);
  // 正在分析的文档id
  const currentRecordId: any = ref(null);
  // 正在分析文档的数据量
  // const currentDataLength: any = ref(0);
  // 上传完成的文档名称
  const uploadFileName: any = ref(null);
  // 正在分析的文档id
  const upLoadRecordId: any = ref(null);
  // 正在分析文档的数据量
  const uploadDataLength: any = ref(0);
  // 1 - 分析数据  2 - 上传数据  3 - 数据列表
  const currentStatus = ref(1);
  // 全部题目
  const allTopics: any = ref([]);
  // 分析loading
  const loadingAnalysis = ref(false);
  // 被选择的通用题目数据
  const commonTopics = computed(() => {
    console.log(
      allTopics.value.map((topic) => ({
        ...topic,
        label: topic.title,
        value: JSON.stringify(unref(topic)),
      }))
    );
    return allTopics.value.map((topic) => ({
      ...topic,
      label: topic.title,
      value: JSON.stringify(unref(topic)),
    }));
  });
  // 分组可选的题目
  const canSelectGroupTopics = computed(() => {
    const topics = allTopics.value.filter((t) => {
      for (const gd of groupData.value) {
        if (gd.items.find((g) => g.name === t.name)) {
          return false;
        }
      }
      return true;
    });
    return topics.map((t) => {
      return {
        ...t,
        label: t.title,
        value: JSON.stringify(unref(t)),
      };
    });
  });
  // 选中的题目
  const groupValue: any = ref([]);
  const showAddModal = ref(false);
  // 添加分组
  const addGroup = () => {
    showAddModal.value = true;
  };
  // 渲染分组穿梭框
  const renderSourceLabel = (option: any) => {
    return h(
      NTooltip,
      {},
      {
        trigger: () =>
          h(
            'span',
            {
              class: 'mr-5 text-left',
              style: {
                width: '100%',
                display: 'block',
                overflow: 'hidden',
                'text-overflow': 'ellipsis',
                'white-space': 'nowrap',
              },
            },
            `${option.option.label}`
          ),
        default: () => h('span', {}, `${option.option.label}`),
      }
    );
  };
  // 分组列
  const groupColumns = [
    // {
    //   type: 'selection',
    // },
    {
      title: '组号',
      width: 300,
      render: (record, index) => {
        return h(NInput, {
          placeholder: '请输入组号',
          defaultValue: record.name.toString(),
          onBlur: (e: any) => {
            const v = e.target?.value;
            const od = [...toRaw(unref(groupData))];
            const r = toRaw(record);
            r.name = v;
            od[index] = r;
            groupData.value = od;
            nextTick(() => {
              genVerifyEquation();
              genStructureModel();
            });
          },
        });
      },
    },
    {
      title: '题目',
      align: 'center',
      render: (record) => {
        return h(
          'div',
          { class: 'flex flex-col items-center mb-2' },
          {
            default: () =>
              record.items.map((item) => {
                return h(
                  NTooltip,
                  {},
                  {
                    trigger: () =>
                      h(
                        'span',
                        {
                          class: 'mr-5 text-center',
                          style: {
                            width: '100%',
                            display: 'block',
                            overflow: 'hidden',
                            'text-overflow': 'ellipsis',
                            'white-space': 'nowrap',
                          },
                        },
                        `${item.title}`
                      ),
                    default: () => h('span', {}, `${item.title}`),
                  }
                );
              }),
          }
        );
      },
    },
    {
      title: '操作',
      width: 200,
      render: (record) => {
        return h(
          NButton,
          { type: 'error', onclick: () => deleteGroup(record) },
          { default: () => '删除' }
        );
      },
    },
  ];
  // 分组列
  const groupColumns1 = [
    // {
    //   type: 'selection',
    // },
    {
      title: '组号',
      width: 300,
      render: (record, index) => {
        return h(NInput, {
          placeholder: '请输入组号',
          defaultValue: record.name.toString(),
          onBlur: (e: any) => {
            const v = e.target?.value;
            const od = [...toRaw(unref(responseGroupData))];
            const r = toRaw(record);
            r.name = v;
            od[index] = r;
            responseGroupData.value = od;
          },
        });
      },
    },
    {
      title: '题目',
      align: 'center',
      render: (record) => {
        return h(
          'div',
          { class: 'flex flex-col items-center mb-2' },
          {
            default: () =>
              record.items.map((item) => {
                return h(
                  NTooltip,
                  {},
                  {
                    trigger: () =>
                      h(
                        'span',
                        {
                          class: 'mr-5 text-center',
                          style: {
                            width: '100%',
                            display: 'block',
                            overflow: 'hidden',
                            'text-overflow': 'ellipsis',
                            'white-space': 'nowrap',
                          },
                        },
                        `${item.title}`
                      ),
                    default: () => h('span', {}, `${item.title}`),
                  }
                );
              }),
          }
        );
      },
    },
    {
      title: '操作',
      width: 200,
      render: (record) => {
        return h(
          NButton,
          { type: 'error', onclick: () => deleteResponseGroup(record) },
          { default: () => '删除' }
        );
      },
    },
  ];
  const deleteResponseGroup = (record) => {
    debugger;
    const index = responseGroupData.value.findIndex((d) => d.uuid === record.uuid);
    if (index > -1) {
      responseGroupData.value.splice(index, 1);
    }
    responseGroupData.value = toRaw(unref(responseGroupData));
  };
  // 确定添加分组
  const confirmAddGroup = () => {
    const originData = [...toRaw(unref(groupData))];
    if (originData) {
      const tmp: any = {};
      tmp.uuid = guid();
      tmp.items = groupValue.value.map((v) => JSON.parse(v));
      // 找所有分组的最大序号
      let no = -Infinity;
      originData.forEach((group: any) => {
        const name = Number(group.name);
        if (!isNaN(name) && name > no) {
          no = name;
        }
      });
      if (no === -Infinity) {
        // 初始化
        no = 0;
      }
      tmp.name = no + 1 + '';
      originData.push(tmp);
    }
    groupData.value = originData;
    showAddModal.value = false;
    groupValue.value = [];
  };
  // 分组数据
  const groupData: any = ref([]);
  // 通用分组数据
  const commonGroupData = computed(() => {
    return groupData.value.map((gd) => ({
      ...gd,
      label: gd.name,
      value: gd.uuid,
    }));
  });
  // 可以选择va的分组
  const canSelectVaGroups = computed(() => {
    const result = groupData.value.filter((dg: any) => {
      if (selectedDa.value.includes(dg.uuid)) {
        return false;
      }
      if (selectedMa.value.includes(dg.uuid)) {
        return false;
      }
      return true;
    });
    return result.map((r) => ({
      ...r,
      label: r.name,
      value: r.uuid,
    }));
  });
  // 可以选择da的分组
  const canSelectDaGroups = computed(() => {
    const result = groupData.value.filter((dg: any) => {
      if (selectedVa.value.includes(dg.uuid)) {
        return false;
      }
      if (selectedMa.value.includes(dg.uuid)) {
        return false;
      }
      if (selectedWa.value.includes(dg.uuid)) {
        return false;
      }
      return true;
    });
    return result.map((r) => ({
      ...r,
      label: r.name,
      value: r.uuid,
    }));
  });
  // 可以选择ma的分组
  const canSelectMaGroups = computed(() => {
    const result = groupData.value.filter((dg: any) => {
      if (selectedDa.value.includes(dg.uuid)) {
        return false;
      }
      if (selectedVa.value.includes(dg.uuid)) {
        return false;
      }
      if (selectedWa.value.includes(dg.uuid)) {
        return false;
      }
      return true;
    });
    return result.map((r) => ({
      ...r,
      label: r.name,
      value: r.uuid,
    }));
  });
  // 可以选择wa的分组
  const canSelectWaGroups = computed(() => {
    const result = groupData.value.filter((dg: any) => {
      if (selectedDa.value.includes(dg.uuid)) {
        return false;
      }
      if (selectedVa.value.includes(dg.uuid)) {
        return false;
      }
      if (selectedMa.value.includes(dg.uuid)) {
        return false;
      }
      return true;
    });
    return result.map((r) => ({
      ...r,
      label: r.name,
      value: r.uuid,
    }));
  });
  // 可以选择的其它变量
  // 选择的分组的标识
  // const groupRowKeys = (row) => row.uuid;
  // // 选中的分组
  const selectedRow: any = ref([]);
  // // 选择和取消分组
  // const handleCheck = (v) => {
  //   selectedRow.value = v;
  // };
  // 删除分组
  const deleteGroup = (record) => {
    const data: any = [];
    const rowKeys: any = [];
    const newSelectedVa: any = [];
    const newSelectedDa: any = [];
    const newSelectedMa: any = [];
    const newSelectedWa: any = [];
    const newTyValue: any = [];
    const newVarianceYValue: any = [];
    // 删除分组数据
    groupData.value.forEach((gd) => {
      if (gd.uuid !== record.uuid) {
        data.push(gd);
      }
    });
    // 删除选择的组
    selectedRow.value.forEach((sr) => {
      if (sr.uuid !== record.uuid) {
        rowKeys.push(sr);
      }
    });
    // 重置变量
    selectedVa.value.forEach((va) => {
      if (va !== record.uuid) {
        newSelectedVa.push(va);
      }
    });
    selectedDa.value.forEach((da) => {
      if (da !== record.uuid) {
        newSelectedDa.push(da);
      }
    });
    selectedMa.value.forEach((ma) => {
      if (ma !== record.uuid) {
        newSelectedMa.push(ma);
      }
    });
    selectedWa.value.forEach((wa) => {
      if (wa !== record.uuid) {
        newSelectedWa.push(wa);
      }
    });
    tyValue.value.forEach((ty) => {
      if (ty !== record.uuid) {
        newTyValue.push(ty);
      }
    });
    varianceYValue.value.forEach((vy) => {
      if (vy !== record.uuid) {
        newVarianceYValue.push(vy);
      }
    });
    selectedVa.value = newSelectedVa;
    selectedDa.value = newSelectedDa;
    selectedMa.value = newSelectedMa;
    selectedWa.value = newSelectedWa;
    tyValue.value = newTyValue;
    varianceYValue.value = newVarianceYValue;
    selectedRow.value = rowKeys;
    groupData.value = data;
  };
  // 选中的自变量
  const selectedDa: any = ref([]);
  // 自变量发生变化
  const updateDa = (_) => {
    genStructureModel();
    genVerifyEquation();
  };
  // 选中的因变量
  const selectedVa: any = ref([]);
  // 因变量发生变化
  const updateVa = (_) => {
    genStructureModel();
    genVerifyEquation();
  };
  // 选中的调节变量
  const selectedWa: any = ref([]);
  // 调节变量发生变化
  const updateWa = (_) => {
    genStructureModel();
    genVerifyEquation();
  };

  // 可以选择控制变量
  const canSelectCa = computed(() => {
    return canSelectGroupTopics.value;
  });
  // 选中的控制变量
  const selectedCa = ref([]);
  // 选中的中介变量
  const selectedMa: any = ref([]);
  // 中介变量发生变化
  const updateMa = (_) => {
    genStructureModel();
    genVerifyEquation();
  };
  // 当前算法
  const currentTab = ref('全局');
  const data = ref([
    {
      name: '全局',
      is_checked: true,
      config: {
        // 因变量
        va: [],
        // 自变量
        da: [],
        // 中介变量
        ma: [],
        // 控制变量
        ca: [] as any,
        // 调节变量
        wa: [],
        // 分组
        groups: [] as any,
      },
      attribute: 0,
    },
    {
      name: '效度',
      is_checked: false,
      config: {},
      attribute: 2,
    },
    {
      name: '信度',
      is_checked: false,
      config: {},
      attribute: 2,
    },
    {
      name: '频数',
      is_checked: false,
      config: {
        // 题目，只能是单选
        items: [],
      },
      attribute: 1,
    },
    {
      name: '多重响应',
      is_checked: false,
      config: {
        // 题目，只能是多选
        items: [],
      },
      attribute: 2,
    },
    {
      name: '描述',
      is_checked: false,
      config: {
        // 题目，只能是单选
        items: [],
      },
      attribute: 2,
    },
    {
      name: '回归',
      is_checked: false,
      config: {},
      attribute: 1,
    },
    {
      name: '相关',
      is_checked: false,
      config: {},
      attribute: 1,
    },
    {
      name: '中介',
      is_checked: false,
      config: {
        // 中介频率
        intermediary_count: 5000,
        // 中介类型
        intermediary_type: 1,
      },
      attribute: 2,
    },
    {
      name: '调节',
      is_checked: false,
      config: {
        // 数据处理
        data_handle_type: 1,
        // 模型选择
        model_type: 1,
      },
      attribute: 2,
    },
    {
      name: 'T检验',
      is_checked: false,
      disabled: true,
      config: {
        // x变量 只能选单选是两个的选项，同时排除分组里面选好的
        x: [] as any,
        // y变量，选择组
        y: [],
      },
      attribute: 1,
    },
    {
      name: '方差',
      is_checked: false,
      disabled: true,
      config: {
        // x变量 只能选单选是两个以上的选项，同时排除分组里面选好的
        x: [],
        // y变量，选择组
        y: [],
      },
      attribute: 1,
    },
    {
      name: '验证性分析',
      is_checked: false,
      config: {
        // 根据自变量、因变量和中介变量选择关系
        relations: [],
      },
      attribute: 2,
    },
    {
      name: '结构模型',
      is_checked: false,
      config: {
        // 根据自变量、因变量和中介变量选择关系
        relations: [],
      },
      attribute: 2,
    },
  ]);
  // 通用方法
  const commonData = computed(() => {
    console.log(data.value);
    return data.value.filter((d) => d.attribute === 1);
  });
  // 问卷研究
  const analysisData = computed(() => {
    return data.value.filter((d) => d.attribute === 2);
  });
  // 选中的模板
  const tmp = ref(1);
  // 模板选择
  const templateData: any = ref([
    {
      label: '模板一',
      value: 1,
    },
    {
      label: '模板二',
      value: 2,
    },
    {
      label: '模板三',
      value: 3,
    },
  ]);
  // 选中的配置
  const selectedAlgorithms = computed(() => {
    return data.value.filter((d) => d.is_checked);
  });
  const tabRef: any = ref(null);
  // 监听配置的选择
  const onConfigChange = (name, v) => {
    if (!v) {
      currentTab.value = '全局';
    }
    tabRef.value?.syncBarPosition();
    const handleAttribute = data.value.find((d) => d.name === name);
    if (handleAttribute) {
      handleAttribute.is_checked = v;
      if (!v) {
        // 重置配置
        handleAttribute.config = {};
      }
    }
    if (name === '验证性分析' && v) {
      genStructureModel();
    }
    if (name === '结构模型' && v) {
      genVerifyEquation();
    }
  };

  // 生成uuid
  function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (Math.random() * 16) | 0,
        v = c == 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }

  // 选中的频数题目
  const selectedPinshuTopics: any = ref([]);
  // 多重响应添加分组
  const addReponseGroup = () => {
    showResponseModal.value = true;
  };
  // 多重响应分组数据
  const responseGroupData: any = ref([]);
  const groupResponseValue: any = ref([]);
  // 多重响应弹出框
  const showResponseModal = ref(false);
  // 分组可选的题目
  const canSelectResponseGroupTopics = computed(() => {
    const topics = allTopics.value.filter((t) => {
      for (const gd of responseGroupData.value) {
        if (gd.items.find((g) => g.name === t.name)) {
          return false;
        }
      }
      return true;
    });
    return topics.map((t) => {
      return {
        ...t,
        label: t.title,
        value: JSON.stringify(unref(t)),
      };
    });
  });
  const confirmAddResponseGroup = () => {
    const originData = [...toRaw(unref(responseGroupData))];
    if (originData) {
      const tmp: any = {};
      tmp.uuid = guid();
      tmp.items = groupResponseValue.value.map((v) => JSON.parse(v));
      // 找所有分组的最大序号
      let no = -Infinity;
      originData.forEach((group: any) => {
        const name = Number(group.name);
        if (!isNaN(name) && name > no) {
          no = name;
        }
      });
      if (no === -Infinity) {
        // 初始化
        no = 0;
      }
      tmp.name = no + 1 + '';
      originData.push(tmp);
    }
    responseGroupData.value = originData;
    showResponseModal.value = false;
    groupResponseValue.value = [];
  };
  // 选中的多重响应题目
  // const selectedResponseTopics: any = ref([]);
  // 选中的描述应题目
  const selectedDesTopics: any = ref([]);
  // 中介抽样次数
  const intermediaryCountOptions = [
    {
      label: '50次',
      value: 50,
    },
    {
      label: '500次',
      value: 500,
    },
    {
      label: '1000次',
      value: 1000,
    },
    {
      label: '2000次',
      value: 2000,
    },
    {
      label: '5000次',
      value: 5000,
    },
  ];
  // 选择的抽样次数
  const selectedintermediaryCount = ref(5000);
  // 中介类型
  const intermediaryTypeOptions = [
    {
      label: '平行中介',
      value: 1,
    },
    {
      label: '链式中介',
      value: 2,
    },
  ];
  // 选择的中介类型
  const selectedintermediaryType = ref(1);
  // 调节数据处理选项
  const adjustDataOptions = [
    {
      label: '中心化',
      value: 1,
    },
    {
      label: '标准化',
      value: 2,
    },
    {
      label: '不处理',
      value: 3,
    },
  ];
  // 调节数据处理
  const adjustDataValue = ref(2);
  // 调节模型选择选项
  const modernOptions = [
    {
      label: '1',
      value: 1,
    },
    {
      label: '7',
      value: 7,
    },
    {
      label: '8',
      value: 8,
    },
    {
      label: '14',
      value: 14,
    },
    {
      label: '15',
      value: 15,
    },
  ];
  // 调节模型选择
  const modernValue = ref(7);
  // T检验X变量
  const txValue = ref([]);
  // T检验Y分组
  const tyValue = ref([]);
  // 方差X变量
  const varianceXValue = ref([]);
  // 方差Y分组
  const varianceYValue = ref([]);

  // 上传数据入口
  const uploadData = () => {
    uploadStatus.value = 1;
    currentStatus.value = 2;
    previewUploadData.value = [];
    previewUploadColumns.value = [];
    uploadFileName.value = null;
    upLoadRecordId.value = null;
    allAnalysis.value = [];
    uploadDataLength.value = 0;
  };
  // 上传数据的状态
  const uploadStatus = ref(1);
  // 上传数据头部应该显示的图片
  const uploadImg = computed(() => {
    return uploadStatus.value === 1 ? UploadDataImg1 : UploadDataImg2;
  });
  // 示例表格数据
  const uploadExampleData = [
    {
      line1: '编号',
      line2: '性别',
      line3: '年龄',
      line4: '学历',
      line5: '年收入',
      line6: '日期',
      line7: '......',
    },
    {
      line1: '1',
      line2: '1',
      line3: '3',
      line4: '2',
      line5: '2',
      line6: '2021/8/12',
      line7: '......',
    },
    {
      line1: '2',
      line2: '1',
      line3: '2',
      line4: '3',
      line5: '2',
      line6: '2021/8/13',
      line7: '',
    },
    {
      line1: '3',
      line2: '2',
      line3: '2',
      line4: '4',
      line5: '2',
      line6: '2021/8/14',
      line7: '',
    },
    {
      line1: '4',
      line2: '2',
      line3: '1',
      line4: '1',
      line5: '3',
      line6: '2021/8/15',
      line7: '',
    },
  ];
  // 示例表格列
  const uploadExampleColumns = [
    {
      title: '第一列',
      key: 'line1',
      align: 'center',
    },
    {
      title: '第二列',
      key: 'line2',
      align: 'center',
    },
    {
      title: '第三列',
      key: 'line3',
      align: 'center',
    },
    {
      title: '第四列',
      key: 'line4',
      align: 'center',
    },
    {
      title: '第五列',
      key: 'line5',
      align: 'center',
    },
    {
      title: '第六列',
      key: 'line6',
      align: 'center',
    },
    {
      title: '......',
      key: 'line7',
      align: 'center',
    },
  ];
  // 上传地址
  const { uploadUrl } = globSetting;
  const uploadDataUrl = uploadUrl + '/api/report/v1/upload_data';
  const downloadDataUrl = uploadUrl + '/api/report/v1/download_data';
  const customRequest = ({
    file,
    data,
    headers,
    withCredentials,
    action,
    onError,
    onProgress,
  }: UploadCustomRequestOptions) => {
    const formData = new FormData();
    if (data) {
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key as keyof UploadCustomRequestOptions['data']]);
      });
    }
    formData.append('file', file.file as File);
    lyla
      .post(action as string, {
        withCredentials,
        headers: headers as Record<string, string>,
        body: formData,
        onUploadProgress: ({ percent }) => {
          onProgress({ percent: Math.ceil(percent) });
        },
      })
      .then(({ json }) => {
        console.log('upload finish --->', json);
        uploadFinish(json);
      })
      .catch((error) => {
        message.success(error.message);
        onError();
      });
  };
  // 上传成功
  const uploadFinish = (result) => {
    if (result.code === 200) {
      uploadFileName.value = result.result?.file_name;
      upLoadRecordId.value = result.result?.record_obj;
      uploadDataLength.value = result.result?.datas.length;
      previewUploadColumns.value = result.result?.title_config.map((t, index) => ({
        title: t.name,
        render: (record) => {
          return record[index];
        },
      }));
      previewUploadData.value = result.result?.datas.slice(0, 20);
      allTopics.value = result.result?.title_config?.map((t) => ({
        title: t.name,
        ...t,
      }));
    }
    uploadStatus.value = 2;
  };
  // 上传失败
  // const uploadError = (e) => {
  //   message.error('上传失败', e);
  // };
  // 预览数据
  const previewUploadData = ref([]);
  // 预览数据列
  const previewUploadColumns = ref([]);
  // 上一步
  const preStep = () => {
    uploadStatus.value = 1;
    previewUploadData.value = [];
    previewUploadColumns.value = [];
    uploadFileName.value = null;
    upLoadRecordId.value = null;
    uploadDataLength.value = 0;
  };
  // 进入分析
  const goAnalysis = () => {
    const address = router.resolve({ name: 'Analysis', query: { id: upLoadRecordId.value } });
    window.open(location.origin + address.href, '_blank');
  };
  // 分页
  const page = ref(1);
  const pageSize = ref(10);
  const pageCount = ref(0);
  // 数据列表入口
  const goDataList = () => {
    showFiles.value = true;
    currentStatus.value = 3;
    listFile({
      page_num: unref(page) - 1,
      page_size: unref(pageSize),
    }).then((res) => {
      showFiles.value = false;
      pageCount.value = Math.ceil(res.total_size / unref(pageSize));
      allAnalysis.value = res.list;
    });
  };
  // 页数或者每页数量变化
  const pullList = () => {
    goDataList();
    allAnalysis.value = [];
  };
  // 正在分析的数据
  const currentAnalysis = ref([]);
  // 全部分析的数据
  const allAnalysis = ref([]);
  // 加载数据的状态
  const showFiles = ref(false);
  // 分析数据的列
  const createAnalysisColumns = (t: string) => [
    {
      title: '日期',
      width: 140,
      key: 'upload_time',
      render: (record) => {
        return dayjs(record.upload_time).format('YYYY-MM-DD');
      },
    },
    {
      title: '文档名称',
      key: 'file_name',
      render: (record) => {
        return h(NInput, {
          defaultValue: record.file_name,
          onBlur: (e: any) => {
            const v = e.target?.value;
            modifyFileName({
              record_id: record.record_id,
              file_name: v,
            }).then(() => {
              message.success('名称修改成功！');
              goDataList();
            });
          },
        });
      },
    },
    {
      title: '操作',
      key: '__',
      width: 240,
      render: (record) => {
        return h(
          NSpace,
          {},
          {
            default: () => [
              h(
                NButton,
                {
                  type: 'primary',
                  size: 'small',
                  onClick: () => {
                    const address = router.resolve({
                      name: 'Analysis',
                      query: { id: record.record_id },
                    });
                    window.open(location.origin + address.href, '_blank');
                  },
                },
                { default: () => (t === 'current' ? '继续分析' : '立即分析') }
              ),
              h(
                NButton,
                {
                  type: 'success',
                  size: 'small',
                  onClick: () => {
                    downLoadFile(record.record_id);
                  },
                },
                { default: () => '下载' }
              ),
              h(
                NButton,
                {
                  type: 'error',
                  size: 'small',
                  onClick: () => {
                    deleteFile({
                      record_id: record.record_id,
                    }).then(() => {
                      message.success('删除成功！');
                      goDataList();
                    });
                  },
                },
                { default: () => '删除' }
              ),
            ],
          }
        );
      },
    },
  ];
  // 下载数据
  const downLoadFile = (id) => {
    const a = document.createElement('a');
    a.href = `${downloadDataUrl}?record_id=${id}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
  // 结构模型数据
  const structureModelGroups: any = ref([]);
  // 验证性方程数据
  const verifyEquationGroups: any = ref([]);
  // 生成结构模型数据
  const genStructureModel = () => {
    const newStructureModelGroups: any = [];
    let no = 999;
    selectedVa.value.forEach((sd) => {
      selectedDa.value.forEach((sv) => {
        newStructureModelGroups.push({
          fromUuid: sd,
          fromName: groupData.value.find((dg) => dg.uuid === sd)?.name,
          toUuid: sv,
          toName: groupData.value.find((dg) => dg.uuid === sv)?.name,
          is_selected: true,
          sort: no--,
        });
      });
    });
    selectedVa.value.forEach((sm) => {
      selectedMa.value.forEach((sv) => {
        newStructureModelGroups.push({
          fromUuid: sm,
          fromName: groupData.value.find((dg) => dg.uuid === sm)?.name,
          toUuid: sv,
          toName: groupData.value.find((dg) => dg.uuid === sv)?.name,
          is_selected: true,
          sort: no--,
        });
      });
    });
    selectedMa.value.forEach((sd) => {
      selectedDa.value.forEach((sm) => {
        newStructureModelGroups.push({
          fromUuid: sd,
          fromName: groupData.value.find((dg) => dg.uuid === sd)?.name,
          toUuid: sm,
          toName: groupData.value.find((dg) => dg.uuid === sm)?.name,
          is_selected: true,
          sort: no--,
        });
      });
    });
    let vaLength = selectedVa.value.length;
    let daLength = selectedDa.value.length;
    let maLength = selectedMa.value.length;
    while (vaLength--) {
      if (vaLength) {
        const fromUuid = selectedVa.value[vaLength];
        for (let i = 0; i < vaLength; i++) {
          const toUuid = selectedVa.value[i];
          newStructureModelGroups.push({
            fromUuid: fromUuid,
            fromName: groupData.value.find((dg) => dg.uuid === fromUuid)?.name,
            toUuid: toUuid,
            toName: groupData.value.find((dg) => dg.uuid === toUuid)?.name,
            is_selected: true,
            sort: no--,
          });
        }
      }
    }
    while (daLength--) {
      if (daLength) {
        const fromUuid = selectedDa.value[daLength];
        for (let i = 0; i < daLength; i++) {
          const toUuid = selectedDa.value[i];
          newStructureModelGroups.push({
            fromUuid: fromUuid,
            fromName: groupData.value.find((dg) => dg.uuid === fromUuid)?.name,
            toUuid: toUuid,
            toName: groupData.value.find((dg) => dg.uuid === toUuid)?.name,
            is_selected: true,
            sort: no--,
          });
        }
      }
    }
    while (maLength--) {
      if (maLength) {
        const fromUuid = selectedMa.value[maLength];
        for (let i = 0; i < daLength; i++) {
          const toUuid = selectedMa.value[i];
          newStructureModelGroups.push({
            fromUuid: fromUuid,
            fromName: groupData.value.find((dg) => dg.uuid === fromUuid)?.name,
            toUuid: toUuid,
            toName: groupData.value.find((dg) => dg.uuid === toUuid)?.name,
            is_selected: true,
            sort: no--,
          });
        }
      }
    }
    structureModelGroups.value = newStructureModelGroups;
  };
  // 生成验证性方程数据
  const genVerifyEquation = () => {
    // 自变量 -> 因变量  自变量 -> 中介变量  中介变量 -> 因变量
    const newVerifyEquationGroups: any = [];
    let no = 999;
    selectedVa.value.forEach((sd) => {
      selectedDa.value.forEach((sv) => {
        newVerifyEquationGroups.push({
          fromUuid: sd,
          fromName: groupData.value.find((dg) => dg.uuid === sd)?.name,
          toUuid: sv,
          toName: groupData.value.find((dg) => dg.uuid === sv)?.name,
          is_selected: true,
          sort: no--,
        });
      });
    });
    selectedVa.value.forEach((sm) => {
      selectedMa.value.forEach((sv) => {
        newVerifyEquationGroups.push({
          fromUuid: sm,
          fromName: groupData.value.find((dg) => dg.uuid === sm)?.name,
          toUuid: sv,
          toName: groupData.value.find((dg) => dg.uuid === sv)?.name,
          is_selected: true,
          sort: no--,
        });
      });
    });
    selectedMa.value.forEach((sd) => {
      selectedDa.value.forEach((sm) => {
        newVerifyEquationGroups.push({
          fromUuid: sd,
          fromName: groupData.value.find((dg) => dg.uuid === sd)?.name,
          toUuid: sm,
          toName: groupData.value.find((dg) => dg.uuid === sm)?.name,
          is_selected: true,
          sort: no--,
        });
      });
    });
    verifyEquationGroups.value = newVerifyEquationGroups;
  };
  // 删除验证方程数据
  let verifyMin = -1;
  const delVerifyGroup = (group) => {
    group.is_selected = false;
    group.sort = verifyMin--;
    const newVerifyEquationGroups = [
      ...toRaw(unref(verifyEquationGroups)).sort((x, y) => Number(y.sort) - Number(x.sort)),
    ];
    verifyEquationGroups.value = newVerifyEquationGroups;
  };
  // 增加验证方程数据
  const addVerifyGroup = (group) => {
    group.is_selected = true;
    group.sort =
      verifyEquationGroups.value.reduce((prev, cur) => {
        return Math.max(Number(cur.sort), prev);
      }, -Infinity) + 1;
    const newVerifyEquationGroups = [
      ...toRaw(unref(verifyEquationGroups)).sort((x, y) => Number(y.sort) - Number(x.sort)),
    ];
    verifyEquationGroups.value = newVerifyEquationGroups;
  };
  let structureMin = -1;
  // 删除结构模型
  const delStructure = (struc) => {
    struc.is_selected = false;
    struc.sort = structureMin--;
    const newStructureModelGroups = [
      ...toRaw(unref(structureModelGroups)).sort((x, y) => Number(y.sort) - Number(x.sort)),
    ];
    structureModelGroups.value = newStructureModelGroups;
  };
  // 增加结构模型
  const addStructure = (struc) => {
    struc.is_selected = true;
    struc.sort =
      structureModelGroups.value.reduce((prev, cur) => {
        return Math.max(Number(cur.sort), prev);
      }, -Infinity) + 1;
    const newStructureModelGroups = [
      ...toRaw(unref(structureModelGroups)).sort((x, y) => Number(y.sort) - Number(x.sort)),
    ];
    structureModelGroups.value = newStructureModelGroups;
  };
  // 回到首页
  const goIndex = () => {
    currentStatus.value = 1;
    previewUploadData.value = [];
    previewUploadColumns.value = [];
    upLoadRecordId.value = null;
    uploadFileName.value = null;
    uploadDataLength.value = 0;
    analysisStatus.value = 0;
    allAnalysis.value = [];
  };
  // 初始化数据
  onMounted(() => {
    const { id } = route.query;
    if (id) {
      currentRecordId.value = id;
      serachData({
        record_id: id,
      }).then((res) => {
        currentFileName.value = res.file_name;
        allTopics.value = res.titles.map((t) => ({
          title: t.name,
          ...t,
        }));
        queryConfig({ record_id: id }).then((res) => {
          if (res?.has_config) {
            init(res?.config);
          }
        });
      });
    }
  });
  const init = (config: any) => {
    data.value = config;
    // 全局配置 分组 因变量  自变量  控制变量  中介变量 调节变量
    const globalConfig = config.find((algorithm) => algorithm.name === '全局')?.config;
    if (globalConfig) {
      // 分组数据 groupData
      groupData.value = globalConfig.groups;
      // 因变量 selectedDa
      selectedDa.value = globalConfig.da;
      // 自变量 selectedVa
      selectedVa.value = globalConfig.va;
      // 中介变量 selectedMa
      selectedMa.value = globalConfig.ma;
      // 调节变量 selectedWa
      selectedWa.value = globalConfig.wa;
      // 控制变量 canSelectCa
      selectedCa.value = globalConfig.ca.map((c) => {
        const topic = canSelectCa.value.find((t) => t.tid === c.tid);
        if (topic) {
          return topic.value;
        }
      });
    }
    // 频数
    const pinshuConfig = config.find((algorithm) => algorithm.name === '频数');
    if (pinshuConfig?.is_checked) {
      console.log(pinshuConfig, commonTopics.value)
      selectedPinshuTopics.value = pinshuConfig.config?.items?.map((item) => {
        const topic = commonTopics.value.find((commonTopic) => commonTopic.tid === item.tid);
        if (topic) {
          return topic.value;
        }
      });
      console.log(selectedPinshuTopics.value)
    }
    // 多重响应
    const responseGroupConfig = config.find((algorithm) => algorithm.name === '多重响应');
    if (responseGroupConfig?.is_checked) {
      responseGroupData.value = responseGroupConfig.config?.items;
    }
    // 描述 selectedDesTopics
    const desConfig = config.find((algorithm) => algorithm.name === '描述');
    if (desConfig?.is_checked) {
      selectedDesTopics.value = desConfig.config?.items.map((item) => {
        const topic = commonTopics.value.find((commonTopic) => commonTopic.tid === item.tid);
        if (topic) {
          return topic.value;
        }
      });
    }
    // 中介
    const mediaryConfig = config.find((algorithm) => algorithm.name === '中介');
    if (mediaryConfig?.is_checked) {
      selectedintermediaryCount.value = mediaryConfig.config?.intermediary_count;
      selectedintermediaryType.value = mediaryConfig.config?.intermediary_type;
    }
    // 调节
    const adjustConfig = config.find((algorithm) => algorithm.name === '调节');
    if (adjustConfig?.is_checked) {
      adjustDataValue.value = adjustConfig.config?.data_handle_type;
      modernValue.value = adjustConfig.config?.model_type;
    }
    // 验证性分析 structureModelGroups
    const structureConfig = config.find((algorithm) => algorithm.name === '验证性分析');
    if (structureConfig?.is_checked) {
      structureModelGroups.value = structureConfig.config?.relations;
    }
    // 结构模型
    const verifyConfig = config.find((algorithm) => algorithm.name === '结构模型');
    if (verifyConfig?.is_checked) {
      verifyEquationGroups.value = verifyConfig.config?.relations;
    }
  };
  const analysisStatus = ref(0);
  const currentBuffer: any = ref(null);
  const currentPdfBlob: any = ref(null);
  // 开始分析
  const startAnalysis = () => {
    loadingAnalysis.value = true;
    // 校验数据
    if (!currentRecordId.value) {
      loadingAnalysis.value = false;
      message.error('请上传分析的数据或者选择分析数据！');
      return;
    }
    for (const selectedAlgorithm of selectedAlgorithms.value) {
      switch (selectedAlgorithm.name) {
        case '频数':
          if (selectedPinshuTopics.value.length < 1) {
            message.error('请选择频数的题目！');
            loadingAnalysis.value = false;
            currentTab.value = '频数';
            return;
          }
          break;
        case 'T检验':
          if (txValue.value.length < 1 || tyValue.value.length < 1) {
            message.error('请选择T检验配置！');
            loadingAnalysis.value = false;
            currentTab.value = 'T检验';
            return;
          }
          break;
        case '方差':
          if (varianceXValue.value.length < 1 || varianceYValue.value.length < 1) {
            message.error('请选择方差配置！');
            loadingAnalysis.value = false;
            currentTab.value = '方差';
            return;
          }
          break;
        case '描述':
          if (selectedDesTopics.value.length < 1) {
            message.error('请选择描述的题目！');
            loadingAnalysis.value = false;
            currentTab.value = '描述';
            return;
          }
          break;
        case '多重响应':
          if (responseGroupData.value.length < 1) {
            message.error('请对多重响应分组！');
            loadingAnalysis.value = false;
            currentTab.value = '多重响应';
            return;
          }
          break;
        case '调节':
          if (!adjustDataValue.value || !modernValue.value) {
            message.error('请选择调节的题目！');
            loadingAnalysis.value = false;
            currentTab.value = '调节';
            return;
          }
          break;
        case '验证性分析':
          if (structureModelGroups.value.length < 1) {
            message.error('请选择验证性分析的配置！');
            loadingAnalysis.value = false;
            currentTab.value = '验证性分析';
            return;
          }
          break;
        case '结构模型':
          if (verifyEquationGroups.value.length < 1) {
            message.error('请选择结构模型的配置！');
            loadingAnalysis.value = false;
            currentTab.value = '结构模型';
            return;
          }
          break;
        case '中介':
          if (!selectedintermediaryCount.value || !selectedintermediaryType.value) {
            message.error('请选择中介的配置！');
            loadingAnalysis.value = false;
            currentTab.value = '中介';
            return;
          }
          break;
        case '回归':
          if (selectedVa.value.length < 1 || selectedDa.value.length < 1) {
            message.error('请选择回归的配置！');
            loadingAnalysis.value = false;
            currentTab.value = '全局';
            return;
          }
        default:
          break;
      }
    }
    // 组装数据
    const config = [...toRaw(unref(data))];
    config.forEach((algorithm) => {
      if (algorithm.is_checked) {
        switch (algorithm.name) {
          case '频数':
            console.log(selectedPinshuTopics.value)
            algorithm.config.items = unref(selectedPinshuTopics).map((p) => JSON.parse(p));
            break;
          case '全局':
            algorithm.config.ca = toRaw(unref(selectedCa)).map((tmp) => JSON.parse(tmp));
            algorithm.config.da = toRaw(unref(selectedDa));
            algorithm.config.va = toRaw(unref(selectedVa));
            algorithm.config.ma = toRaw(unref(selectedMa));
            algorithm.config.wa = toRaw(unref(selectedWa));
            algorithm.config.groups = toRaw(unref(groupData));
            break;
          case 'T检验':
            algorithm.config.x = unref(txValue).map((p) => JSON.parse(p));
            algorithm.config.y = unref(tyValue);
            break;
          case '方差':
            algorithm.config.x = unref(varianceXValue).map((p) => JSON.parse(p));
            algorithm.config.y = unref(varianceYValue);
            break;
          case '多重响应':
            algorithm.config.items = toRaw(unref(responseGroupData));
            break;
          case '描述':
            algorithm.config.items = unref(selectedDesTopics).map((p) => JSON.parse(p));
            break;
          case '中介':
            algorithm.config.intermediary_count = unref(selectedintermediaryCount);
            algorithm.config.intermediary_type = unref(selectedintermediaryType);
            break;
          case '调节':
            algorithm.config.data_handle_type = unref(adjustDataValue);
            algorithm.config.model_type = unref(modernValue);
            break;
          case '验证性分析':
            algorithm.config.relations = toRaw(unref(structureModelGroups));
            break;
          case '结构模型':
            algorithm.config.relations = toRaw(unref(verifyEquationGroups));
            break;
          default:
            break;
        }
      }
    });
    algorithmAnalysis({
      record_id: route.query.id,
      config,
    })
      .then((res) => {
        analysisStatus.value = 1;
        currentBuffer.value = res;
        nextTick(() => {
          loadingAnalysis.value = false;
          docx
            .renderAsync(res, docWrapper.value)
            .then((x) => console.log(x, 'finished'))
            .catch((e) => console.log('docx error', e));
        });
      })
      .catch(() => {
        message.error('未知错误！');
        loadingAnalysis.value = false;
      });
  };
  const downloadFile = (blob, filename) => {
    const blobUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.download = filename;
    a.style.display = 'none';
    a.target = '_self';
    a.href = blobUrl;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
  const loadingDownloadWord = ref(false);
  const loadingDownloadPdf = ref(false);
  const downloadPdf = async () => {
    loadingDownloadPdf.value = true;
    if (currentPdfBlob.value && currentFileName.value) {
      await downloadFile(unref(currentPdfBlob), unref(currentFileName) + '.pdf');
      loadingDownloadPdf.value = false;
      return;
    }
    loadingDownloadPdf.value = false;
    message.error('未知错误！');
  };
  const downloadWord = async () => {
    loadingDownloadWord.value = true;
    if (currentBuffer.value && currentFileName.value) {
      await downloadFile(unref(currentBuffer), unref(currentFileName) + '.docx');
      loadingDownloadWord.value = false;
      return;
    }
    loadingDownloadWord.value = false;
    message.error('未知错误！');
  };
</script>

<style scoped>
  .bg-wrapper {
    background-color: rgb(235, 238, 245);
  }
  .analysis-wrapper {
    background-color: rgb(235, 238, 245);
    min-height: 100vh;
    padding-bottom: 40px;
  }
  .analysis-header {
    display: flex;
    justify-content: space-between;
    height: 60px;
    background-color: rgb(255, 255, 255);
    margin-bottom: 15px;
    align-items: center;
  }
  .header-title {
    color: rgb(23, 138, 236);
    font-size: 24px;
    margin-left: 16px;
  }
  .bg-white {
    background-color: rgb(255, 255, 255);
  }
  .attribute-header {
    border-bottom: 1px solid rgba(167, 165, 165, 0.2);
  }
  .attribute-wrapper {
    width: 300px;
  }
  li {
    list-style: none;
  }
</style>
